﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.IdentityModel.Web;
using System.Security.Cryptography;
using System.Xml;

namespace AccessControlLibrary
{
    /// <summary>
    /// Encrypts cookies using the 3DES algorithm
    /// </summary>
    class TripleDESCookieTransform : CookieTransform
    {
        private TripleDESCryptoServiceProvider tripleDes;

        /// <summary>
        /// Default constructor
        /// </summary>
        /// <remarks>
        /// This constructor throws an exception because the encryption key and initialization vector must be specified.
        /// </remarks>
        public TripleDESCookieTransform()
        {
            throw new InvalidOperationException("You must specify the 3DES encryption key and initialization vector.");
        }

        /// <summary>
        /// Constructor with encryption key and initialization vector specified
        /// </summary>
        public TripleDESCookieTransform(byte[] key, byte[] vector)
        {
            tripleDes = new TripleDESCryptoServiceProvider();
            tripleDes.Key = key;
            tripleDes.IV = vector;
        }

        public override byte[] Decode(byte[] encoded)
        {
            ICryptoTransform ITransform = tripleDes.CreateDecryptor();
            return ITransform.TransformFinalBlock(encoded, 0, encoded.Length);
        }

        public override byte[] Encode(byte[] value)
        {
            ICryptoTransform ITransform = tripleDes.CreateEncryptor();
            return ITransform.TransformFinalBlock(value, 0, value.Length);
        }
    }
}
